package com.blockmeta.bbs.businesslibrary.websocket;

import java.util.concurrent.ConcurrentLinkedQueue;

public class PacketBase extends Thread
{
	protected ConcurrentLinkedQueue<QuePkt>	m_msgQueue;
	protected BlockMetaSocket.IPacketEventListener m_pktListener = null;

	public PacketBase()
	{
		m_msgQueue = new ConcurrentLinkedQueue<QuePkt>();

		setDaemon(true);
		start();
	}

	public void run()
	{
//		Looper.prepare();
//		Looper.loop();
		while(true)
		{
			QuePkt pkt = m_msgQueue.poll();

			if (pkt == null)
			{
				waitQueState();
				continue;
			}
			else
			{
				onFireEvent(pkt);
			}
		}
	}

	public void setPacketEventListener(BlockMetaSocket.IPacketEventListener listener)
	{
		m_pktListener = listener;
	}

	public void dispatch(int what, int session, Object packet, int type)
	{
		QuePkt pkt = new QuePkt(what, session, packet, type);

		m_msgQueue.add(pkt);
		notifyQueState(pkt);
	}

	protected synchronized void notifyQueState(QuePkt pkt)
	{
		notify();
	}

	protected synchronized void waitQueState()
	{
		try
		{
			wait();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
	}

	protected void onFireEvent(QuePkt pkt)
	{
		if (m_pktListener != null)
		{
			m_pktListener.onPacket(pkt.m_nWhat, pkt.m_nSession, pkt.m_objPacket, pkt.m_nType);
		}
	}

	protected class QuePkt
	{
		public int 		m_nWhat;
		public int 		m_nSession;
		public int 		m_nType;
		public Object	m_objPacket;

		public QuePkt(int what, int session, Object packet, int type)
		{
			m_nWhat     = what;
			m_nSession  = session;
			m_nType     = type;
			m_objPacket = packet;
		}
	}
}
